import java.util.Arrays;

/**
 * Created by xiebang
 * Description
 * User:小谢
 * Date:2021-12-06
 * Time:10:24
 */
public class MyArraysList {
    public int[] elem;
    public int usedSize;
    public static int capacity = 10;
    public MyArraysList(){
        this.elem = new int[capacity];
    }
    //插入数据
    public void add(int pos,int val){

        if (pos > usedSize || pos < 0){
                System.out.println("位置不合法");
                return;
        }else {
            if (isfull()){
                this.elem = addCapacity();
            }
            for (int i = this.usedSize; i >pos ; i--) {
                this.elem[i] = this.elem[i - 1];
            }
            this.elem[pos] = val;
            this.usedSize++;
        }
    }
    //
    public boolean isfull (){
        return this.usedSize == capacity;
    }
    public int[] addCapacity(){
        this.elem = Arrays.copyOf(this.elem,2*capacity);
        capacity = capacity * 2;
        return this.elem;
    }

    public void display(){
        for (int i = 0; i < usedSize; i++) {
            System.out.print(this.elem[i] + " -> ");
        }
        System.out.print("null");
        System.out.println();
    }
    public boolean isEmpty(){
        return this.usedSize == 0;
    }
    public boolean contains(int toFind){
        if (isEmpty()) return false;
        for (int i = 0; i < this.usedSize; i++) {
            if (this.elem[i] == toFind){
                return true;
            }
        }
        return false;
    }

    public int search(int toFind){
        if (isEmpty()) return -1;
        for (int i = 0; i < this.usedSize; i++) {
            if (this.elem[i] == toFind){
                return i;
            }

        }
        return -1;
    }

    public int getPos(int pos){
        if (isEmpty()) throw  new RuntimeException("顺序表为空");
        if (pos< 0 || pos >= this.usedSize){
            System.out.println("坐标非法");
            throw new RuntimeException("坐标非法");
        }
        return this.elem[pos];
    }

    public int size (){
        return this.usedSize;
    }

    //给pos位置设置值
    public void setPos(int pos,int val){
        if (pos < 0 || pos >= this.usedSize){
            throw new RuntimeException("pos位置不合法");
        }
        if (isEmpty()){
            throw  new RuntimeException("顺序表为空");
        }

        this.elem[pos] = val;
    }

    //删除第一次出现的key值
    public void remove(int key){
        if (isEmpty()){
            throw  new RuntimeException("顺序表为null");
        }
        if (contains(key)){
            for (int i = search(key); i < this.usedSize; i++) {
                this.elem[i] = this.elem[i+1];
            }
            this.usedSize--;
        }else {
            System.out.println("没有这个数字");
            return;
        }
    }
    public void clean(){
        for (int i = 0; i < this.usedSize; i++) {
            this.elem[i] =0;
        }
        this.elem = null;
        this.usedSize = 0;
    }
}
